import 'package:flutter/material.dart' show debugPrint;
import 'package:hive/hive.dart';

import '../index.dart';

class ReportService {
  static const String _boxName = 'reports';

  static Future<void> initialize() async {
    // 注册适配器（必须在打开box之前）
    if (!Hive.isAdapterRegistered(6)) {
      Hive.registerAdapter(ReportTypeAdapter());
    }
    if (!Hive.isAdapterRegistered(7)) {
      Hive.registerAdapter(ReportReasonAdapter());
    }
    if (!Hive.isAdapterRegistered(8)) {
      Hive.registerAdapter(ReportEntityAdapter());
    }

    // 打开reports数据盒子
    await Hive.openBox<ReportEntity>(_boxName);
  }

  /// 提交举报
  static Future<bool> submitReport({
    required String reporterId,
    required String targetId,
    required ReportType type,
    required ReportReason reason,
    String? description,
  }) async {
    try {
      final box = Hive.box<ReportEntity>(_boxName);
      
      // 生成举报ID
      final reportId = DateTime.now().millisecondsSinceEpoch.toString();
      
      // 创建举报记录
      final report = ReportEntity(
        id: reportId,
        reporterId: reporterId,
        targetId: targetId,
        type: type,
        reason: reason,
        timestamp: DateTime.now(),
        description: description,
      );

      // 保存举报记录
      await box.put(reportId, report);

      // 更新用户的举报列表
      await _updateUserReportList(reporterId, targetId, type);

      debugPrint('举报提交成功: $report');
      return true;
    } catch (e) {
      debugPrint('举报提交失败: $e');
      return false;
    }
  }

  /// 更新用户的举报列表
  static Future<void> _updateUserReportList(
    String reporterId,
    String targetId,
    ReportType type,
  ) async {
    try {
      final currentUser = UserService.getCurrentUser();
      if (currentUser == null || currentUser.id != reporterId) return;

      List<String> updatedReportedPosts = List.from(currentUser.reportedPosts);
      List<String> updatedReportedUsers = List.from(currentUser.reportedUsers);
      List<String> updatedReportedChats = List.from(currentUser.reportedChats);

      switch (type) {
        case ReportType.post:
          if (!updatedReportedPosts.contains(targetId)) {
            updatedReportedPosts.add(targetId);
          }
          break;
        case ReportType.user:
          if (!updatedReportedUsers.contains(targetId)) {
            updatedReportedUsers.add(targetId);
          }
          break;
        case ReportType.chat:
          if (!updatedReportedChats.contains(targetId)) {
            updatedReportedChats.add(targetId);
          }
          break;
      }

      final updatedUser = currentUser.copyWith(
        reportedPosts: updatedReportedPosts,
        reportedUsers: updatedReportedUsers,
        reportedChats: updatedReportedChats,
      );

      await UserService.updateUser(updatedUser);
    } catch (e) {
      debugPrint('更新用户举报列表失败: $e');
    }
  }

}
